package com.hdkj.eduservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdkj.eduservice.entity.EduCourse;
import com.hdkj.eduservice.entity.EduCourseDescription;
import com.hdkj.eduservice.entity.frontvo.CourseFrontVo;
import com.hdkj.eduservice.entity.frontvo.CourseWebVo;
import com.hdkj.eduservice.entity.vo.CourseInfoVo;
import com.hdkj.eduservice.entity.vo.CoursePublishVo;
import com.hdkj.eduservice.mapper.EduCourseMapper;
import com.hdkj.eduservice.service.EduChapterService;
import com.hdkj.eduservice.service.EduCourseDescriptionService;
import com.hdkj.eduservice.service.EduCourseService;
import com.hdkj.eduservice.service.EduVideoService;
import com.hdkj.handler.GuiliException;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author 贾佩雨
 * @since 2022-05-09
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {
    //课程描述注入
    @Autowired
    private EduCourseDescriptionService courseDescriptionService;

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private RedisTemplate redisTemplate;

    //注入分布式锁
    @Autowired
    private RedissonClient redissonClient;

    //TODO 将前端传入的isDelete 添加到CourseInfoVo中，并设置默认值  0
    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {

//1 向课程表添加课程基本信息
        //CourseInfoVo对象转换eduCourse对象
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if (insert == 0) {
            //添加失败
            throw new GuiliException(20001, "添加课程信息失败");
        }

        //获取添加之后课程id
        String cid = eduCourse.getId();

        //2 向课程简介表添加课程简介
        //edu_course_description
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        //设置描述id就是课程id
        courseDescription.setId(cid);
        courseDescriptionService.save(courseDescription);
        return cid;
    }

    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        //1 查询课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse, courseInfoVo);

        //2 查询描述表
        EduCourseDescription courseDescription = courseDescriptionService.getById(courseId);
        courseInfoVo.setDescription(courseDescription.getDescription());

        return courseInfoVo;
    }

    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
//1 修改课程表
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        int update = baseMapper.updateById(eduCourse);
        if (update == 0) {
            throw new GuiliException(20001, "修改课程信息失败");
        }

        //2 修改描述表
        EduCourseDescription description = new EduCourseDescription();
        description.setId(courseInfoVo.getId());
        description.setDescription(courseInfoVo.getDescription());
        courseDescriptionService.updateById(description);

    }

    @Override
    public CoursePublishVo publishCourseInfo(String id) {
        //调用mapper
        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(id);
        return publishCourseInfo;

    }

    @Override
    public void removeCourse(String courseId) {
        //1 根据课程id删除小节
        eduVideoService.removeVideoByCourseId(courseId);

        //2 根据课程id删除章节
        eduChapterService.removeChapterByCourseId(courseId);

        //3 根据课程id删除描述
        courseDescriptionService.removeById(courseId);

        //4 根据课程id删除课程本身
        int result = baseMapper.deleteById(courseId);
        if (result == 0) { //失败返回
            throw new GuiliException(20001, "删除失败");
        }
    }

    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> pageParam, CourseFrontVo courseFrontVo) {
        //2 根据讲师id查询所讲课程
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())) { //一级分类
            wrapper.eq("subject_parent_id", courseFrontVo.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectId())) { //二级分类
            wrapper.eq("subject_id", courseFrontVo.getSubjectId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) { //关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) { //最新
            wrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {//价格
            wrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam, wrapper);

        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();//下一页
        boolean hasPrevious = pageParam.hasPrevious();//上一页

        //把分页数据获取出来，放到map集合
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        //map返回
        return map;

    }

    //根据课程id，编写sql语句查询课程信息
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);

    }


    //    @Cacheable(value = "course",key = "'selectcourseList'")
    @Override
    public List<EduCourse> getcourselist() throws InterruptedException {
/**
 * @apiNote
 * 查找数据库
 */
//        QueryWrapper<EduCourse> courseWrapper = new QueryWrapper<>();
//        courseWrapper.orderByDesc("id");
//        courseWrapper.last("limit 8");
//        List<EduCourse> courseList = baseMapper.selectList(courseWrapper);
//        return courseList;
//    }
/**
 * @apiNote
 * 整合redis
 */
        ValueOperations ops = redisTemplate.opsForValue();
        String course = (String) ops.get("course");

        if (StringUtils.isEmpty(course)) {

//            String s1 = UUID.randomUUID().toString();
            RLock lock = redissonClient.getLock("lock");
            //开始加锁，同时设置失效时间，防止死锁/不加也会有redisson中的看门狗自动续期
            lock.lock(30, TimeUnit.SECONDS);
            QueryWrapper<EduCourse> courseWrapper = new QueryWrapper<>();
            courseWrapper.orderByDesc("id");
            courseWrapper.last("limit 8");
            List<EduCourse> courseList = baseMapper.selectList(courseWrapper);
            //将courseList转变成json数据并且存到redis缓存中去、
            String s = JSON.toJSONString(courseList);
            ops.set("course", s, 1, TimeUnit.DAYS);
//            解锁
            lock.unlock();

            return courseList;

        } else {
            List<EduCourse> courseList = JSON.parseObject(course, new TypeReference<List<EduCourse>>() {
            });
            return courseList;
        }

    }
}

